package cn.loioi.distribution.spring.db;

import java.sql.SQLException;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import cn.loioi.distribution.db.DbExecute;
import cn.loioi.distribution.db.DbManger;

public class SpringDbManger extends DbManger {

	private PlatformTransactionManager transactionManager;

	public void setTransactionManager(PlatformTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	@Override
	public SpringDbConnoction getConnoction() throws SQLException {
		return new SpringDbConnoction(dataSource);
	}

	@Override
	public <B> B transactionExecute(DbExecute<B> execute) throws Exception {
		B result = null;

		if (transactionManager != null) {
			// 创建事务状态
			TransactionDefinition definition = new DefaultTransactionDefinition();
			TransactionStatus status = transactionManager.getTransaction(definition);
			// 获取连接
			SpringDbConnoction connoction = getConnoction();
			connoction.setTransactionStatus(status);

			try {
				// 执行查询
				result = execute.execute(connoction);
				// 判断是否需要回滚
				if (connoction.isRollbackOnly()) {
					transactionManager.rollback(status);
				} else {
					transactionManager.commit(status);
				}
			} catch (Exception e) {
				transactionManager.rollback(status);

				throw e;
			} finally {
				if (connoction != null) connoction.close();
			}
		} else {
			result = super.transactionExecute(execute);
		}

		return result;
	}
}
